import java.util.HashMap;
import java.util.Scanner;

public class MembershipSystem {
    private static final String FILENAME = "supermarket.dat";

    public static void main(String[] args) {
        Supermarket supermarket = readSupermarketFromFile();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("请选择操作：1. 开卡 2. 查询积分 3. 退出");
            int choice = scanner.nextInt();
            scanner.nextLine(); 

            switch (choice) {
                case 1:
                    System.out.println("输入姓名：");
                    String name = scanner.nextLine();
                    System.out.println("输入卡号：");
                    String cardNumber = scanner.nextLine();
                    Member member = new Member(cardNumber, name);
                    supermarket.addMember(member);
                    saveSupermarketToFile(supermarket);
                    System.out.println("开卡成功！");
                    break;
                case 2:
                    System.out.println("输入卡号：");
                    String queryCardNumber = scanner.nextLine();
                    Member queriedMember = supermarket.getMember(queryCardNumber);
                    if (queriedMember != null) {
                        System.out.println("剩余积分：" + queriedMember.getPoints());
                    } else {
                        System.out.println("会员不存在！");
                    }
                    break;
                case 3:
                    saveSupermarketToFile(supermarket);
                    System.out.println("退出系统。");
                    return;
                default:
                    System.out.println("无效的操作。");
                    break;
            }
        }
    }

    private static Supermarket readSupermarketFromFile() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILENAME))) {
            return (Supermarket) ois.readObject();
        } catch (FileNotFoundException e) {
            return new Supermarket("MySupermarket", "123 Main St");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void saveSupermarketToFile(Supermarket supermarket) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILENAME))) {
            oos.writeObject(supermarket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
